package com.tyut.controller;

import com.tyut.pojo.Article;
import com.tyut.pojo.PageBean;
import com.tyut.pojo.Result;
import com.tyut.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 增加文章
     * @param article 传入的文章信息
     * @return 增加文章成功
     */
    //@Validated 对文章内容进行校验
    @PostMapping
    public Result Add(@RequestBody Article article){
        String title = article.getTitle();
        String content = article.getContent();
        String coverImg = article.getCoverImg();
        Integer categoryId = article.getCategoryId();
        if (title == null || content == null || coverImg == null || categoryId == null
            ||title =="" || content =="" || coverImg ==""){
            return Result.error("文章信息不完整");
        }
        if (title.length() > 10){
            return Result.error("文章标题不能超过10个字符");
        }
        if (content.length() > 3300){
            return Result.error("文章内容不能超过3300个字符");
        }
        articleService.add(article);
        return Result.success("增加文章成功");
    }

    /**
     *  查询文章列表
     * @param pageNum 页码
     * @param pageSize 每页显示的条数
     * @param categoryId 分类id
     * @param state 发布状态
     * @return 查询的文章列表
     */
    @GetMapping
    public Result<PageBean<Article>> list(Integer pageNum,Integer pageSize,@RequestParam(required = false) Integer categoryId,@RequestParam(required = false) String state, @RequestParam(required = false) String checkState){
        PageBean<Article> pageBean = articleService.list(pageNum,pageSize,categoryId,state, checkState);
        return Result.success(pageBean);
    }

    /**
     * 查看文章详情
     * @param id 文章id
     * @return 根据id查询的文章内容
     */
    @GetMapping("/detail")
    public Result<Article> detail(Integer id){
        return Result.success(articleService.detail(id));
    }

    /**
     * 更新文章信息
     * @param article 传入的更新文章信息
     * @return 更新文章成功
     */
    @PutMapping
    public Result update(@RequestBody @Validated Article article){
        articleService.update(article);
        return Result.success();
    }

    /**
     *  删除文章
     * @param id 文章id
     * @return 删除文章成功
     */
    @DeleteMapping
    public Result delete(Integer id){
        articleService.delete(id);
        return Result.success();
    }

    @PutMapping("/check")
    public Result check(Article article){
        articleService.check(article);
        return Result.success();
    }


}
